# -*- coding: UTF-8 -*-
__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-2-26 17:39:27"
__version = "0.1"

import re
#import logging
from datetime import datetime, timedelta
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

#from lib.scrypto import scrypto
from lib.usercookie import usercookie
from OauthProxy import OauthProxy
from config import config

class UserLog(webapp.RequestHandler):
    def get(self):
        process(self, method='GET')
    def post(self):
        process(self, method='POST')

def process(handler, method):
    tpl = config.tpl_path + 'login.html'
    response = handler.response
    request = handler.request
    if re.match('/login/?', request.path, re.IGNORECASE):
        if method == 'GET':
            response.out.write(template.render(tpl, {'error': False}))
            return
        
        name = request.get('user').encode('utf-8')
        pwd = request.get('pass').encode('utf-8')
        rem = request.get('remenber').encode('utf-8')
        oauth = OauthProxy(name, pwd)
        tokens = oauth.getTokens()
        if tokens is not None:
            gtwkey = usercookie.encrypt(tokens)
            format = '%a, %d-%b-%Y %H:%M:%S'
            current = datetime.utcnow()
            expires = config.session
            if rem:
                expires = config.cookie
            delta = timedelta(minutes = expires)
            expires = current + delta
            gtwexpires = expires.strftime(format) + ' GMT'
            response.headers['Set-Cookie'] =  config.cookie_name + '=' + gtwkey + '; path=/; expires=' + gtwexpires
            response.headers['Location'] = '/'
            response.set_status(302)
        else:
            #logging.error('login error:\n%s\n%s\n%s' % (name, pwd, rem))
            response.out.write(template.render(tpl, {'error': 'Cann\'t access you account!'}))
    else:
        response.headers['Set-Cookie'] =  config.cookie_name + '=; path=/; expires=' + (datetime.utcnow().strftime('%a, %d-%b-%Y %H:%M:%S') + ' GMT')
        response.out.write(template.render(tpl, {'error': False}))
    
    return
